﻿using System;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;
using RS.Common;
using RS.SAAS.Common;
using RS.SAAS.Common.Cookies;
using RS.Web;

namespace TimeManagementMobile.Controllers
{
    public class ControllerBase : Controller
    {
        public ControllerBase()
        {
            ErrorProcessor = new ErrorProcessor();
        }

        public ErrorProcessor ErrorProcessor { get; private set; }

        protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
        {
            LogAppender.SetData(User.Identity.IsAuthenticated ? User.Identity.Name : null, null);

            SetLanguage();

            return base.BeginExecuteCore(callback, state);
        }

        public void SetLanguage(string userLiso = null)
        {
            string cultureName = CookiesManager.CultureName;

            if (!string.IsNullOrWhiteSpace(Request.QueryString["liso"]))
                cultureName = Request.QueryString["liso"];

            if (string.IsNullOrWhiteSpace(cultureName))
                cultureName = CultureHelper.DefaultCulture;

            if (!string.IsNullOrWhiteSpace(userLiso))
                cultureName = userLiso;

            cultureName = CultureHelper.GetImplementedCulture(cultureName);

            CookiesManager.CultureName = cultureName;

            Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
        }
    }
}